import { Component } from 'react'
import Taro from '@tarojs/taro'
import {View, Text, ScrollView} from '@tarojs/components'
import './index.scss'
import global from '../../global';
import { Button, Map, Swiper, SwiperItem, Picker, Input, Image } from '@tarojs/components'
import Request from "../../api";
import Event from "../../event";
export default class Index extends Component {

  constructor(props) {
    super(props);
    this.state = {
      userInfo: {},
      banners: [],
      notices: [{
        title: '永裕小程序上线啦'
      }],
      news: [],
      bindingVillageName: '',
      bindingVillages: [],
      jobReminds: 0,
      noticeReminds: 0,
      rentHouseReminds: 0,
      messageReminds: 0
    }
    // this.getLoginCode = this.getLoginCode.bind(this);
    // this.checkRegisterInfo = this.checkRegisterInfo.bind(this);
    this.getLatestUserInfo = this.getLatestUserInfo.bind(this);
    this.commonNavigate = this.commonNavigate.bind(this);
    this.updateRemindStatus = this.updateRemindStatus.bind(this);
    Event.on('loginFinish', () => {
      console.log("loginfinshing....")
      this.getLatestUserInfo();
    } );
    Event.on('getSystemInfo', (systemInfo) => {
      let { userInfo, banners, notices, news } = systemInfo;
      this.setState({
        userInfo,
        banners,
        notices,
        news
      })
    });
    Event.on('checkOperationRemind', (operationRemind) => {
      let {JOB, NOTICE, RENT_HOUSE, REFLASH_LOGIN_INFO, MESSAGE_LEFT} = operationRemind;
      this.setState({
        jobReminds: JOB.length,
        noticeReminds: NOTICE.length,
        rentHouseReminds: RENT_HOUSE.length,
        messageReminds: MESSAGE_LEFT.length
      });
      global.messageReminds = MESSAGE_LEFT.length;
      if (REFLASH_LOGIN_INFO.length > 0) {
        this.getLatestUserInfo();
        this.updateRemindStatus(REFLASH_LOGIN_INFO[0]);
      }
    })
  }


  componentWillMount () { }

  componentWillUnmount () { }

  componentDidHide () { }

  async updateRemindStatus(operationRemind) {
    try {
      let res = await Request.get(`/business/operation_remind/updateStatus/${operationRemind.businessId}/REFLASH_LOGIN_INFO/${global.userInfo.userId}`);
      if (res.data.code !== 200) {
        throw new Error();
      }
      console.log(res.data.data)
    } catch (e) {
      console.log("更新状态异常")
    }
  }

  /**
   * 获取最新得用户数据
   * @returns {Promise<void>}
   */
  async getLatestUserInfo() {
    if (!global.userInfo.userId) {
      return;
    }
    let res = await Request.get(`/business/wx_user/getInfoWithAuth/${global.userInfo.userId}`);
    if (res.data.code !== 200) {
      console.log('获取最新用户数据失败');
    }
    global.userInfo = res.data.data;
    this.setState({
      userInfo: res.data.data,
      bindingVillages: res.data.data.bindings,
    })
    if (res.data.data.bindings.length > 0) {
      this.setState({
        bindingVillageName: res.data.data.bindings[0].villageName
      })
      global.currentBindingVillage = res.data.data.bindings[0];
    }
  }

  /**
   * 处理绑定小区逻辑
   * @returns {Promise<void>}
   */
  async handleBindHousingEstate() {
    if (global.isLogin && global.userInfo.ownerAuthStatus === '0') {
      await Taro.navigateTo({
        url: '/pages/binding/index'
      });
      return;
    }
    if (!global.isRegister || global.isLogin) {
      await Taro.switchTab({
        url: '/pages/mine/index'
      });
      return;
    }
  }

  /**
   * 扫码开门
   * @returns {Promise<void>}
   */
  async scanToOpen() {
    if (!global.isLogin) {
      await Taro.showModal({
        title: '提示',
        content: '您尚未登录',
        confirmText: '去登录',
        success: (res) =>  {
          if (res.confirm) {
            Taro.switchTab({
              url: '/pages/mine/index'
            })
          }
        }
      });
      return;
    }
    if (!global.userInfo.bindingVillageId || global.userInfo.ownerAuthStatus === '0') {
      await Taro.showModal({
        title: '提示',
        content: '您尚未绑定小区',
        confirmText: '去绑定',
        success: (res) => {
          if (res.confirm) {
            Taro.navigateTo({
              url: '/pages/binding/index'
            })
          }
        }
      });
      return;
    }

    if (global.userInfo.ownerAuthStatus === '1') {
      await Taro.showModal({
        title: '提示',
        content: '您的业主认证正在审核中，请等候审核通过',
        confirmText: '确定',
      });
      return;
    }

    let scanRes = await Taro.scanCode({
      scanType: 'qrCode'
    })
    await Taro.showLoading({
      title: '开门中...'
    })
    let msg = '开门成功'
    try {
      console.log(scanRes)
      let res = await Request.get(`/wx/openGate/${scanRes.result}`);
      if (res.data.code !== 200) {
        msg = '开门失败，请尝试使用门禁机开门';
        throw new Error();
      }
    } catch (e) {
      console.log(e);
      console.log('开门异常')
    } finally {
      await Taro.hideLoading();
      await Taro.showModal({
        title: '提示',
        content: msg
      })
    }
  }

  async commonNavigate(url) {
    if (!global.isLogin) {
      await Taro.showModal({
        title: '提示',
        content: '您尚未登录',
        confirmText: '去登录',
        success: (res) =>  {
          if (res.confirm) {
            Taro.switchTab({
              url: '/pages/mine/index'
            })
          }
        }
      });
      return;
    }
    if (!global.userInfo.bindingVillageId || global.userInfo.ownerAuthStatus === '0') {
      await Taro.showModal({
        title: '提示',
        content: '您尚未绑定小区',
        confirmText: '去绑定',
        success: (res) => {
          if (res.confirm) {
            Taro.navigateTo({
              url: '/pages/binding/index'
            })
          }
        }
      });
      return;
    }

    if (global.userInfo.ownerAuthStatus === '1') {
      await Taro.showModal({
        title: '提示',
        content: '您的业主认证正在审核中，请等候审核通过',
        confirmText: '确定',
      });
      return;
    }
    await Taro.navigateTo({
      url: url
    })
  }

  onVillageChange(e) {
    this.setState({
      bindingVillageName: this.state.bindingVillages[e.detail.value].villageName
    })
    global.currentBindingVillage = this.state.bindingVillages[e.detail.value];
    Event.emit("updateSystemInfo", global.currentBindingVillage);
  }

  render () {

    let { userInfo, banners, notices, news} = this.state;

    let villageBindingStatusComponent = <Text>未绑定小区</Text>;

    if (userInfo.ownerAuthStatus === '1') {
      villageBindingStatusComponent = <Text>业主认证中</Text>;
    } else if (userInfo.ownerAuthStatus === '2') {
      villageBindingStatusComponent = [
        <Picker mode='selector' range={this.state.bindingVillages} rangeKey='villageName' onChange={this.onVillageChange.bind(this)}>
          <View className='picker'>
            {this.state.bindingVillageName}
          </View>
        </Picker>,
        <Text className='iconfont icon-arrow-down-bold size34 no_binding_icon'/>
      ]
      // villageBindingStatusComponent = <Text>{userInfo.bindingVillageName}</Text>;
    }

    let bannersComponents = banners.map(item => (
      <SwiperItem>
        <Image className='swiper_image' mode={"scaleToFill"} src={Request.imgHost + item.imageUrl}/>
      </SwiperItem>
    ));

    let noticesComponents = notices.map(item => (
      <SwiperItem onClick={async () => {
        global.noticeText = item.content;
        global.currentNotice = item;
        await Taro.navigateTo({
          url: '/pages/notice/index'
        })
      }}>
        <View className='notice_item'>
          <View className='dot'/>
          <Text>{item.title}</Text>
        </View>
      </SwiperItem>
    ))
    if (notices.length === 0) {
      noticesComponents = [
        <SwiperItem>
          <View className='notice_item'>
            <View className='dot'/>
            <Text>暂未最新公告！</Text>
          </View>
        </SwiperItem>
      ]
    }

    return (
      <View className='index'>
        <View className='top_info_container' style={global.safePaddingTopStyle}>
          <View className='housing_info'>
            {villageBindingStatusComponent}
          </View>
          <View className='action_container'>
            <View className='search_input'>
              <Text className='iconfont icon-sousuo color-grey size36'/>
              <Input type='text' placeholder='请输入关键字'/>
            </View>
            <Text style={{marginLeft: '10px'}}  onClick={this.scanToOpen.bind(this)} className='iconfont icon-saoyisao color-444 size50'/>
            <Text style={{marginLeft: '10px'}} onClick={() => Taro.navigateTo({url: '/pages/message/index'})} className='iconfont icon-xiaoxizhongxin color-444 size50'/>
            {
              this.state.messageReminds > 0 && <View className={'red_circle'}/>
            }
          </View>
        </View>
        <Swiper
          className='banner-swiper'
          indicatorColor='#00000020'
          indicatorActiveColor='#fff'
          circular
          autoplay={true}
          indicatorDots>
          {
            bannersComponents
          }
        </Swiper>
        <View className='children_app_container'>
          <View className='apps_container'>
            <View className='app_item' onClick={async () => await this.commonNavigate('/pages/recruit_list/index')}>
              <Image src={require('./img/zhaopin.png')}/>
              <Text>招聘信息</Text>
              {
                this.state.jobReminds > 0 && <View className={'red_circle'}/>
              }
            </View>
            <View className='app_item' onClick={this.scanToOpen.bind(this)}>
              <Image src={require('./img/kaimen.png')}/>
              <Text>扫码开门</Text>
            </View>
            <View className='app_item'  onClick={async () => {
              global.isGuest = false;
              await this.commonNavigate('/pages/face_list/index')
            }}>
              <Image src={require('./img/rlsb.png')}/>
              <Text>门禁管理</Text>
            </View>
          </View>
          <View className='apps_container'>
            <View className='app_item' onClick={() => {
              Taro.navigateToMiniProgram({
                appId: 'wxa89720422d3127c4',
                path: '',
                envVersion: 'release',// 打开正式版
                success(res) {
                  // 打开成功
                },
                fail: function (err) {
                  console.log(err);
                }
              })
            }}>
              <Image src={require('./img/bus.png')}/>
              <Text>公交查询</Text>
            </View>
            <View className='app_item' onClick={async () => await this.commonNavigate('/pages/house_rental_list/index')}>
              <Image src={require('./img/fangwuzu.png')}/>
              <Text>房屋出租</Text>
              {
                this.state.rentHouseReminds > 0 && <View className={'red_circle'}/>
              }
            </View>
            <View className='app_item' onClick={async () => await this.commonNavigate('/pages/repair_event_list/index')}>
              <Image src={require('./img/bsbx.png')}/>
              <Text>报事报修</Text>
            </View>
          </View>
        </View>
        <View className='notice_container'>
          <Image src={require('./img/notice.jpg')}></Image>
          <Swiper
            className='notice-swiper'
            vertical
            autoplay
            circular>
            {
              noticesComponents
            }
          </Swiper>
          <View className='iconfont icon-arrow-right color-blue size34'></View>
          {
            this.state.noticeReminds > 0 && <View className={'red_circle'}/>
          }
        </View>
        <View className='news_container'>
          <View className='news_header'>
            <Text className='color-505050'>社区资讯</Text>
            {/*<Text>更多 ></Text>*/}
          </View>
          <ScrollView style={{maxHeight: '350px', paddingLeft: '10px', width: 'calc(100vw - 30px)'}} scrollY={true}>
            {
              news.map(item => (
                <View className='news_item' onClick={async () => {
                  global.newsInfo = {
                    author: item.villageName || '永裕在线',
                    time: item.createTime,
                    content: item.content
                  }
                  await Taro.navigateTo({
                    url: '/pages/new/index'
                  })
                }}>
                  <Image src={Request.imgHost + item.coverImageUrl} />
                  <View className='news_info'>
                    <Text className='news_title color-505050'>
                      {item.title}
                    </Text>
                    <Text className='news_content' l>
                      {
                        item.content.replace(/<\/?[a-zA-Z]+(\s+[a-zA-Z]+=".*")*>/g,'')
                      }
                    </Text>
                    <Text className='news_time'>
                      {item.createTime}
                    </Text>
                  </View>
                  <View style={{width: '16px'}}/>
                </View>
              ))
            }
          </ScrollView>
        </View>
      </View>
    )
  }
}
